package com.uuah.server.config.spring.parsers.collection;

import java.util.Map;

import org.springframework.beans.factory.BeanDefinitionStoreException;
import org.springframework.beans.factory.config.MapFactoryBean;
import org.springframework.beans.factory.support.AbstractBeanDefinition;
import org.springframework.beans.factory.support.BeanDefinitionBuilder;
import org.springframework.beans.factory.xml.ParserContext;
import org.w3c.dom.Element;

import com.uuah.server.config.spring.UuahHierarchicalBeanDefinitionParserDelegate;
import com.uuah.server.config.spring.parsers.AbstractUuahBeanDefinitionParser;

/**
 * Creates a single, stand-alone map object and processes standard Spring sub
 * elements
 */
public class OrphanMapDefinitionParser extends AbstractUuahBeanDefinitionParser {
	private Class mapClass;
	private String name;
	private boolean dynamicName = false;

	public OrphanMapDefinitionParser(Class mapClass) {
		this.mapClass = mapClass;
		dynamicName = true;
	}

	public OrphanMapDefinitionParser(Class mapClass, String name) {
		this.mapClass = mapClass;
		this.name = name;
	}

	protected Class getBeanClass(Element element) {
		return MapFactoryBean.class;
	}

	protected void doParse(Element element, ParserContext parserContext,
			BeanDefinitionBuilder builder) {
		Map parsedMap = parserContext.getDelegate().parseMapElement(element,
				builder.getRawBeanDefinition());
		builder.addPropertyValue("sourceMap", parsedMap);
		builder.addPropertyValue("targetMapClass", mapClass.getName());
		getBeanAssembler(element, builder).setBeanFlag(
				UuahHierarchicalBeanDefinitionParserDelegate.UUAH_NO_RECURSE);
	}

	protected void preProcess(Element element) {
		super.preProcess(element);
		if (dynamicName) {
			name = null;
		}
	}

	protected String resolveId(Element element,
			AbstractBeanDefinition definition, ParserContext parserContext)
			throws BeanDefinitionStoreException {
		return name;
	}
}
